<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="jobName">
        <el-input
          v-model="queryParams.jobName"
          placeholder="请输入任务名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提交模式" prop="deployMode">
        <el-select v-model="queryParams.deployMode" placeholder="请选择提交模式" clearable size="small">
          <el-option
            v-for="dict in deployModeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="运行后的任务id" prop="jobId">
        <el-input
          v-model="queryParams.jobId"
          placeholder="请输入运行后的任务id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="是否开启" prop="isOpen">
        <el-select v-model="queryParams.isOpen" placeholder="请选择是否开启" clearable size="small">
          <el-option
            v-for="dict in isOpenOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <!--<el-form-item label="最后一次启动时间" prop="lastStartTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.lastStartTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择最后一次启动时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['flink:JobConfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['flink:JobConfig:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['flink:JobConfig:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['flink:JobConfig:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="JobConfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="配置Id" align="center" prop="id" />
      <el-table-column label="任务名称" align="center" prop="jobName" />
      <el-table-column label="提交模式" align="center" prop="deployMode" :formatter="deployModeFormat" />
      <el-table-column label="运行后的任务id" align="center" prop="jobId" />
      <!--<el-table-column label="是否开启" align="center" prop="isOpen" :formatter="isOpenFormat" />  -->
      <el-table-column label="是否开启任务" align="center" prop="status">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status !== 1"
            size="mini"
            type="primary"
            icon="el-icon-caret-right"
            @click="handleStartJob(scope.row)"
            v-hasPermi="['flink:JobConfig:start']"
          >提交任务</el-button>
          <el-button
            v-if="scope.row.status == 1"
            size="mini"
            type="danger"
            icon="el-icon-caret-right"
            @click="handleStopJob(scope.row)"
            v-hasPermi="['flink:JobConfig:stop']"
          >停止任务</el-button>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status" :formatter="statusFormat" />
      
      <el-table-column label="最后一次启动时间" align="center" prop="lastStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastStartTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="savePoint" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status == 1"
            size="mini"
            type="warning"
            icon="el-icon-caret-right"
            @click="handleSavepoint(scope.row)"
            v-hasPermi="['flink:JobConfig:savepoint']"
          >备份并停止任务</el-button> 
          <el-button
            v-if="scope.row.status != 1"
            size="mini"
            type="primary"
            icon="el-icon-caret-right"
            @click="handleRecover(scope.row)"
            v-hasPermi="['flink:JobConfig:recover']"
          >备份恢复启动</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['flink:JobConfig:query']"
          >详情</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['flink:JobConfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['flink:JobConfig:remove']"
          >删除</el-button>
        </template>
      </el-table-column>

      <el-table-column label="日志详情" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
              v-hasPermi="['streaming:JobRunLog:query']"
            >详情</el-button>
          </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改flink任务配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-form-item label="任务名称" prop="jobName">
            <el-input v-model="form.jobName" placeholder="请输入任务名称"/>
          </el-form-item> 
          <el-form-item label="提交模式" prop="deployMode">
              <el-select v-model="form.deployMode" placeholder="请选择提交模式">
                <el-option
                  v-for="dict in deployModeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>          
          <el-form-item label="flink运行配置" prop="flinkRunConfig">
            <el-input v-model="form.flinkRunConfig" type="textarea" placeholder="请输入内容" />
          </el-form-item>
  
          <el-form-item label="checkPoint配置" prop="flinkCheckpointConfig">
            <el-input v-model="form.flinkCheckpointConfig" type="textarea" placeholder="请输入内容" />
          </el-form-item>
               
          <el-form-item label="udf地址已经连接器" prop="extJarPath">
            <el-input v-model="form.extJarPath" type="textarea" placeholder="请输入内容" />
          </el-form-item>

          <el-form-item label="sql语句" prop="flinkSql">
            <el-input v-model="form.flinkSql" type="textarea" placeholder="请输入内容"  :autosize="true" />
          </el-form-item>
        </el-row>     
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 日志详情 -->
    <el-dialog :title="title" :visible.sync="openView" width="1000px" append-to-body>
      <el-form ref="logForm" :model="logForm"  label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="Job任务Id" prop="jobConfigId">
              <el-input v-model="logForm.jobConfigId" :disabled="true" />
            </el-form-item>
            <el-form-item label="任务名称" prop="jobName">
              <el-input v-model="logForm.jobName"  :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提交模式" prop="deployMode">
              <el-input v-model="logForm.deployMode" :disabled="true" />
            </el-form-item>
            <el-form-item label="运行后的任务id" prop="jobId">
              <el-input v-model="logForm.jobId" :disabled="true" />
            </el-form-item> 
          </el-col>

          <el-form-item label="启动时本地日志：" prop="localLog">
            <el-input v-model="logForm.localLog" type="textarea" :autosize="true" :disabled="true" />
          </el-form-item>
          <el-form-item label="远程日志url的地址：" prop="localLog">
            <el-input v-model="logForm.remoteLogUrl" type="textarea" :disabled="true" />
          </el-form-item>

          <el-col :span="12">
            <el-form-item label="启动时间" prop="startTime">            
              <el-input v-model="logForm.startTime" :disabled="true" />
            </el-form-item>
            
          </el-col>
          <el-col :span="12">
            <el-form-item label="关闭时间" prop="endTime">
              <el-input v-model="logForm.endTime" :disabled="true" />
            </el-form-item>               
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关 闭</el-button>
      </div>  
    </el-dialog>


    <el-dialog :title="savepointTitle" :visible.sync="recoverView" width="1000px" append-to-body>
      <el-table v-loading="loading2" :data="SavepointBackupList" ref="multipleTable"
      :stripe = "true"  
      @row-click ="handleSelection">
        <el-table-column
          width="50px"
          align="center">
          <template slot-scope="scope">
            <el-radio v-model="radioSelected" :label="scope.row.id" @change.native="handleSelection(scope.row)">&nbsp;  </el-radio>
          </template>
        </el-table-column>
        <!-- <el-table-column label="Id" align="center" prop="id" />
        <el-table-column label="Job任务Id" align="center" prop="jobConfigId" /> -->
        <el-table-column label="备份时间" align="center" prop="backupTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.backupTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地址" align="center" prop="savepointPath" />
        
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitJob">确 定</el-button>
        <el-button @click="recoverView = false">取 消</el-button>
      </div>


    </el-dialog>
  </div>
</template>
  </div>
</template>

<script>
import { listJobConfig, getJobConfig, delJobConfig, addJobConfig, updateJobConfig, exportJobConfig ,startJob,stopJob,savepointStop,savepointStart} from "@/api/streaming/JobConfig";
import { getJobRunLog } from "@/api/streaming/JobRunLog";
import { listSavepointBackup } from "@/api/streaming/SavepointBackup";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "JobConfig",
  components: { 
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // flink任务配置表格数据
      JobConfigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 提交模式字典
      deployModeOptions: [],
      // 是否开启字典
      isOpenOptions: [],
      // 任务状态字典
      statusOptions: [],
      // 是否显示日志详细弹出层
      openView: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jobName: null,
        deployMode: null,
        jobId: null,
        isOpen: null,
        status: null,
        lastStartTime: null,
      },
      // 表单参数
      form: {},
      // 日志表单参数
      logForm: {},
      // 表单校验
      rules: {
        jobName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        deployMode: [
          { required: true, message: "提交模式不能为空", trigger: "change" }
        ],
        flinkSql: [
          { required: true, message: "sql语句不能为空", trigger: "blur" }
        ],
        
        version: [
          { required: true, message: "更新版本号 用于乐观锁不能为空", trigger: "blur" }
        ],
        isDeleted: [
          { required: true, message: "更新版本号 用于乐观锁不能为空", trigger: "blur" }
        ],
      },

      // 是否显示备份数据
      recoverView:false,
      // flink任务备份表格数据
      SavepointBackupList:[],
      // 备份表单总数
      savepointTotal:0,
      //遮罩层
      loading2: false,
      // 标题2
      savepointTitle: '',
      // 查询参数
      param: {
        pageNum: 1,
        pageSize: 10,
        jobConfigId: null,
        savepointPath: null,
        backupTime: null,
        isDeleted: null,
      },

      // 单选绑定
      radioSelected: null,
      currentRow: null,
    };
  },
  created() {
    this.getList();
    this.getDicts("flink_config_model").then(response => {
      this.deployModeOptions = response.data;
    });
    this.getDicts("flink_config_isOpen").then(response => {
      this.isOpenOptions = response.data;
    });
    this.getDicts("flink_config_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询flink任务配置列表 */
    getList() {
      this.loading = true;
      listJobConfig(this.queryParams).then(response => {
        this.JobConfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 提交模式字典翻译
    deployModeFormat(row, column) {
      return this.selectDictLabel(this.deployModeOptions, row.deployMode);
    },
    // 是否开启字典翻译
    isOpenFormat(row, column) {
      return this.selectDictLabel(this.isOpenOptions, row.isOpen);
    },
    // 任务状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        jobName: null,
        deployMode: null,
        flinkRunConfig: null,
        flinkSql: null,
        flinkCheckpointConfig: null,
        jobId: null,
        isOpen: null,
        status: null,
        extJarPath: null,
        lastStartTime: null,
        lastRunLogId: null,
        version: null,
        isDeleted: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加flink任务配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getJobConfig(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改flink任务配置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateJobConfig(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addJobConfig(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除flink任务配置编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delJobConfig(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有flink任务配置数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportJobConfig(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },

    /**提交任务 */
    handleStartJob(row){
      const id = row.id;
      this.$confirm('是否确认开启任务"' + row.jobName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return startJob(id);
        }).then(() => {
          this.getList();
          this.msgSuccess("启动成功,请稍后刷新获取");
        })
    },

    /** 停止任务 */
    handleStopJob(row){
      const id = row.id;
      this.$confirm('是否确认停止任务"' + row.jobName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return stopJob(id);
        }).then(() => {
          this.getList();
          this.msgSuccess("停止成功");
        })
    },

    /** 日志详情 */
    handleView(row) {
      const id = row.lastRunLogId;
      getJobRunLog(id).then(response => {
        this.logForm = response.data;
        this.openView = true;  
        this.title = '最后一次启动日志下详情';
      });
    },

    /**
     * savePoint
     */
    handleSavepoint(row){
      const id = row.id;
      this.$confirm('是否确认备份任务"' + row.jobName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return savepointStop(id);
        }).then(() => {
          this.getList();
          this.msgSuccess("任务关闭成功");
        })
    },

    /** 查询savepoint备份地址列表 */
    handleRecover(row){
      const id = row.id;
      this.loading2 =true;
      this.param.jobConfigId=id;
      listSavepointBackup(this.param).then(response => {
        this.SavepointBackupList = response.rows;
        this.savepointTotal = response.total;
        this.loading2 = false;
      }).then(()=>{
        this.savepointTitle = "选择备份数据";
        this.recoverView = true;  
      });
      
    },
    
    /** 表格处理 */
    handleSelection(val) {
      
      console.log(val);
      this.radioSelected = val.id;
      this.currentRow = val;
    },

    

    /** 备份恢复 */
    submitJob: function() {
      const jobId = this.param.jobConfigId;
      if(null == this.currentRow){
        this.msgSuccess("请选择需要恢复的备份");
        return;
      }
      const savepointId = this.currentRow.id;
      debugger;
      savepointStart(jobId, savepointId).then( response=>{
        this.msgSuccess("启动中，请稍后刷新");
        this.recoverView = false;
        this.getList();
      });
    },
    

  }
};
</script>
